/**
 * 
 */
package org.tiger.netty.server.handler;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author liuwenlai
 */
public class TigerNettyServer {

	private static Logger logger = LoggerFactory.getLogger(TigerNettyServer.class);

	private final int port;

	private String address;

	public TigerNettyServer() {
		this.port = 8089;
		this.address = "127.0.0.1";
	}

	public TigerNettyServer(int port, String address) {
		this.port = port;
		this.address = address;
	}

	public void start() throws Exception {
		// 为什么是final 匿名接口形参 编译后 使用方式 参数一致性
		final TigerServerHandler serverHandler = new TigerServerHandler();
		EventLoopGroup group = new NioEventLoopGroup();
		try{

			ServerBootstrap bootstrap = new ServerBootstrap();

			bootstrap.group(group).channel(NioServerSocketChannel.class)
					.localAddress(new InetSocketAddress(address, port))
					.childHandler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel sc) throws Exception {
							sc.pipeline().addLast(serverHandler);
						}
					});

			// sync 阻塞直到绑定完成
			ChannelFuture future = bootstrap.bind().sync();
			future.channel().closeFuture().sync();
		} catch (Exception e){
			logger.error("start server error:" + e);
		}
	}

	public static void main(String[] args) {

		try{
			if (args.length == 0){
				new TigerNettyServer().start();
			} else{
				int port = Integer.valueOf(args[0]);
				new TigerNettyServer(port, args[1]).start();
			}
		} catch (Exception e){

		}

	}
}
